/*
 * Galaxium Messenger
 * Copyright (C) 2007 Ben Motmans <ben.motmans@gmail.com>
 * Copyright (C) 2003 Philippe Durand <draekz@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;

namespace Galaxium.Core
{
	public static class BitUtility
	{
		private static bool _machineIsLittleEndian;

		static BitUtility ()
		{
			_machineIsLittleEndian = BitConverter.IsLittleEndian;
		}

		public static int ToInt32 (byte[] data, int startIndex, bool dataIsLittleEndian)
		{
			if (_machineIsLittleEndian == dataIsLittleEndian) {
				//the machine has the same endianess as the data, no need to swap bytes
				return BitConverter.ToInt32 (data, startIndex);
			} else {
				byte[] swap = GetSwappedByteArray (data, startIndex, 4);
				return BitConverter.ToInt32 (swap, startIndex);
			}
		}

		public static long ToInt64 (byte[] data, int startIndex, bool dataIsLittleEndian)
		{
			if (_machineIsLittleEndian == dataIsLittleEndian) {
				//the machine has the same endianess as the data, no need to swap bytes
				return BitConverter.ToInt64 (data, startIndex);
			} else {
				byte[] swap = GetSwappedByteArray (data, startIndex, 8);
				return BitConverter.ToInt64 (swap, startIndex);
			}
		}
		
		public static byte[] FromInt32 (int val, bool littleEndian)
		{
			byte[] bytes = BitConverter.GetBytes (val);
			
			if (_machineIsLittleEndian == littleEndian)
				return bytes;
			
			return GetSwappedByteArray (bytes, 0, 4);
		}
		
		public static byte[] FromInt64 (long val, bool littleEndian)
		{
			byte[] bytes = BitConverter.GetBytes (val);
			
			if (_machineIsLittleEndian == littleEndian)
				return bytes;
			
			return GetSwappedByteArray (bytes, 0, 8);
		}

		private static byte[] GetSwappedByteArray (byte[] data, int startIndex, int length)
		{
			byte[] swap = new byte[length];
			while (--length >= 0)
				swap[length] = data[startIndex + length];
			return swap;
		}
	}
}